package com.frejoys.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.admin.*;
import com.frejoys.common.enums.ESite;
import com.frejoys.common.enums.EUserRole;
import com.frejoys.common.enums.EUserStatus;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.EncryptUtil;
import com.frejoys.common.util.RedisUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.vo.admin.AdminListVo;
import com.frejoys.common.vo.admin.UserAgentVo;
import com.frejoys.common.vo.admin.UserVo;
import com.frejoys.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Tag(name = "用户管理", description = "后台用户管理")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixAdmin)
@Authorization(Authority.Private)
public class AdminUserController {

    private final UserService userService;

    private final RedisUtil redisUtil;

    private final RedissonClient redissonClient;



    @Operation(summary = "用户列表")
    @PostMapping("/user/list")
    public Result<IPage<UserVo>> storeList(@RequestBody @Validated UserListDto dto) {
        return Result.success(userService.listUser(dto));
    }

    @Operation(summary = "商家列表")
    @PostMapping("/user/business/list")
    public Result<IPage<UserVo>>  businessList(@RequestBody @Validated UserListDto dto) {
        return Result.success(userService.listBusiness(dto, EUserRole.store.getValue()));
    }


    @Operation(summary = "退出登录")
    @PostMapping("/user/logout")
    public Result logout() {
        userService.logout(RequestUtil.userId(), ESite.admin.getValue(), RequestUtil.siteType());
        return Result.success();
    }

    /**
     * 修改用户密码
     */
    @Operation(summary = "修改用户密码")
    @PostMapping("/user/changePassword")
    Result<String> changePassword(@RequestBody @Validated PasswordChangeDto dto) {
        // 解密
        dto.setNewPassword(EncryptUtil.adminAes.decryptStr(dto.getNewPassword()));
        dto.setOldPassword(EncryptUtil.adminAes.decryptStr(dto.getOldPassword()));

        String lockKey = CacheKeyUtil.changePasswordLockCacheKey(RequestUtil.userId(), ESite.admin.getValue());

        if (redisUtil.setNxEx(lockKey, 1, 5L)) {
                userService.changePassword(dto,RequestUtil.userId());
        }
        // 删除锁
        redisUtil.del(lockKey);
        return Result.success();
    }

    /**
     * 修改用户角色
     */
    @Operation(summary = "修改用户角色")
    @PostMapping("/user/changeRole")
    Result<String> changeRole(@RequestBody @Validated RoleChangeDto dto) {

        RLock lock = redissonClient.getLock(CacheKeyUtil.upUserRoleLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {
                userService.changeRole(dto);
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }
        return Result.success();
    }

    /**
     * 修改用户状态
     */
    @Operation(summary = "修改用户状态")
    @PostMapping("/user/changeUserStatus")
    Result<String> changeUserStatus(@RequestBody @Validated UserStatusChangeDto dto) {
        if (!dto.getStatus().equals(EUserStatus.forbidden.getValue()) && !dto.getStatus().equals(EUserStatus.normal.getValue())) {
            throw new GeneralException(HttpStatus.argumentNotValid);
        }
        userService.upStatus(dto.getUserId(),dto.getStatus());
        return Result.success();
    }

    /**
     * 后台设置用户管理
     */
    @Operation(summary = "后台设置用户管理角色")
    @PostMapping("/user/changeUserRole")
    public  Result setUserRole(@RequestBody @Validated UserRoleDto dto){
        userService.setUserRole(dto);
        return Result.success();
    }


    @PostMapping("/user/agentListInfo")
    @Operation(summary = "查询代理人列表")
    public Result<IPage<UserAgentVo>> agentListInfo(@RequestBody @Validated UserNameAndPhoneDto dto){
        return Result.success(userService.agentListInfo(dto));
    }

    @PostMapping("/user/agentList")
    @Operation(summary = "商家管理-查询代理人列表")
    public Result<IPage<UserAgentVo>> agentList(@RequestBody @Validated UserNameAndPhoneDto dto){
        return Result.success(userService.agentListInfo(dto));
    }


    @PostMapping("/user/notGroupingAgentList")
    @Operation(summary = "添加职员查询代理人列表 +代理组信息")
    public Result<IPage<UserAgentVo>> notGroupingAgentList(@RequestBody @Validated UserNameAndPhoneDto dto){
        return Result.success(userService.notGroupingAgentList(dto));
    }

    @PostMapping("/user/notCustodianList")
    @Operation(summary = "添加组长查询代理人列表 +代理组信息")
    public Result<IPage<UserAgentsVo>> notCustodianList(@RequestBody @Validated NotCustodianDto dto){
        return Result.success(userService.notCustodianList(dto));
    }

    @PostMapping("/user/adminList")
    @Operation(summary = "查看管理员列表")
    public Result<IPage<AdminListVo>> adminList(@RequestBody @Validated UserNameAndPhoneDto dto){
        return Result.success(userService.adminList(dto));
    }
}
